package cn.xny.basic.interceptor;

import cn.xny.basic.jwt.JwtUtils;
import cn.xny.basic.jwt.LoginData;
import cn.xny.basic.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token
        String token = request.getHeader("token");
        //如果有token，通过token获取Redis的登录信息
        if (token != null) {
            try {
                //解密之后获取登录信息
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);

                return true;
            } catch (ExpiredJwtException e) {


                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print("{\"success\":false,\"msg\":\"timeout\"}");

                return false;
            }

        }
        //判断token，如果为null - 直接拦截 响应前端 - 跳转到登录页面
        //如果登录信息为null - 过期了 直接拦截 响应前端 - 跳转到登录页面

        //跳转到登录页面 - 后端跳不了，因为后端项目没有页面 - 放在前端跳转
        //告诉浏览器我要给你响应一个json数据，编码集为utf-8
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(" {\"success\":false,\"msg\":noLogin\"}");

        return false;
    }
}




